package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.behavior.entity.ApReadBehavior;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.IApReadBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.common.util.JsonUtils;
import com.heima.model.article.msg.ArticleBehaviorMsg;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.heima.common.constants.message.HotArticleConstants.HOT_ARTICLE_SCORE_STREAM_TOPIC;

/**
 * <p>
 * APP阅读行为表 服务实现类
 * </p>
 *
 * @author heima
 * @since 2021-03-23
 */
@Service
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements IApReadBehaviorService {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public void saveReadBehavior(ReadBehaviorDto dto) {
        //1、设置属性，判断是否是用户还是设备操作
        Boolean isUser=false;
        //2、获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId!=null && userId!=0){
            isUser=true;
        }
        //3、校验请求参数
        if(userId==null && dto.getEquipmentId()==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //4、查询用户或者设备是否阅读过该文章
        QueryWrapper<ApReadBehavior> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApReadBehavior::getArticleId,dto.getArticleId());
        if(isUser){
            queryWrapper.lambda().eq(ApReadBehavior::getApUserId,userId);
        }else{
            queryWrapper.lambda().eq(ApReadBehavior::getEquipmentId,dto.getEquipmentId());
        }
        //执行查询
        ApReadBehavior readBehavior = this.getOne(queryWrapper);
        if(readBehavior==null){
            //记录阅读行为
            readBehavior = new ApReadBehavior();
            readBehavior.setArticleId(dto.getArticleId());
            if(isUser){
                readBehavior.setApUserId(userId);
            }else {
                readBehavior.setEquipmentId(dto.getEquipmentId());
            }
            readBehavior.setCount(dto.getCount());
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setLoadDuration(dto.getLoadDuration());
            readBehavior.setCreatedTime(new Date());
            this.save(readBehavior);
        }else {
            //更新阅读行为数据
            //更新阅读次数
            readBehavior.setCount(readBehavior.getCount()+dto.getCount());
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setPercentage(dto.getPercentage());
            this.updateById(readBehavior);
        }

        ArticleBehaviorMsg articleBehaviorMsg = new ArticleBehaviorMsg(
                dto.getArticleId(),1,ArticleBehaviorMsg.ArticleBehaviorType.VIEWS
        );
        kafkaTemplate.send(HOT_ARTICLE_SCORE_STREAM_TOPIC, JsonUtils.toString(articleBehaviorMsg));
    }
}
